package com.apes.fn.scm.crossCompany.transfer.service;

import com.apes.fn.scm.crossCompany.transfer.repository.BatchDumpRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service("batchDumpTransferService")
public class BatchDumpTransferService extends DomainService {
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void updateErrorReason(/*String message, String batchId, String receiptLocationId, String productId*/Map condi) {
        String note = condi.get("NOTE").toString();
        String batchId = condi.get("BATCH_DUMP_ID").toString();
        String receiptLocationId = condi.get("RECEIPT_LOCATION_ID").toString();
        String productId = "";
        String sql = " UPDATE STOCK_BATCH_DUMP_ITEM SET NOTE = '"+ note +"' WHERE BATCH_DUMP_ID = '"+ batchId +"' " +
                " AND RECEIPT_LOCATION_ID = '"+ receiptLocationId +"' AND DOWNSTREAM_DOCUMENT IS NULL AND NOTE IS NULL ";
        if (StringUtils.isEmpty(condi.get("PRODUCT_ID"))) {
            String errorProductSql = "SELECT PRODUCT_ID FROM STOCK_BATCH_DUMP_ITEM WHERE INSTR('" + note + "', PRODUCT_ID) > 0 AND BATCH_DUMP_ID = '" + batchId + "' AND RECEIPT_LOCATION_ID = '" + receiptLocationId + "'";
            List products = SpringManager.getBean(BatchDumpRepository.class).findAll(errorProductSql);
            if (products.size() > 0) productId = products.get(0).toString();
        } else {
            productId = String.valueOf(condi.get("PRODUCT_ID"));
        }
        if (StringUtils.hasText(productId)) {
            sql += " AND PRODUCT_ID = '"+ productId +"' ";
        }
        SpringManager.getBean(BatchDumpRepository.class).exec(sql);

        System.out.println();
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void invokeUpdate(SimpleRequest request) {
        this.updateErrorReason(request.getMap());
    }
}
